package com.dgut.uhrs.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 设置忽略静态资源的身份认证
     */
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/css/**", "/img/**", "/**/*.png");
    }

    /**
     * 配置自定义的登录界面，并设置允许所有人访问(必须)。
     * 注意：post请求是默认有CSRF保护。请在自定义的登录界面的表单中加入CSRF令牌一并提交。或配置.csrf().disable()；
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //登录页所有人可以访问
        http.authorizeRequests()
                .antMatchers("/admin/toAdminLogin").permitAll()
                .antMatchers("/user/**").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN");
        //没有权限跳到登录页面
        http.formLogin()
                .loginPage("/admin/toAdminLogin")
                .loginProcessingUrl("/login")
                // 设置默认身份认证成功后跳转的页面,即直接访问登录界面时，认证成功后跳转的页面。
                .defaultSuccessUrl("/admin/toAdminIndex");
        //注销
        http.logout().logoutSuccessUrl("/admin/toAdminLogin");
        //设置跨域访问
        http.cors();
        http.csrf().disable();
        //开启记住我功能
        http.rememberMe().rememberMeParameter("remember");
        //允许iframe
        http.headers().frameOptions().disable();
        //把自定义的SecurityConfigurer应用到安全过滤链
        http.apply(new DgutCasConfig<>());
    }
    @Override
    //定制认证规则
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication()
//                .passwordEncoder(new BCryptPasswordEncoder())
//                .withUser("sakura").password(new BCryptPasswordEncoder().encode("123456")).roles("ADMIN");
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }
}



